'''
Created on Mar 22, 2011
@author: Eric
'''
import subprocess

class WifiScanner(object):
    '''
    Scans Wifi using provided interface.
    '''

    def __init__(self,interface=''):
        '''
        Constructor
        '''
        self._interface = interface
        self._macList = []
        self._chanList = []
        self._encrboolList = []
        self._ssidList = []
        self._encryptList = []
    
    def scanWifi(self):
        '''
        Scans wifi using the interface that was provided and splits the results into instance lists.
        '''
        scan = subprocess.Popen(['/sbin/iwlist',self._interface,'scan'],stdout=subprocess.PIPE)
        stdout, stderr =  scan.communicate()
        lines = stdout.split('\n')
        lines = lines[1:]
        data = []
        for i in lines:
            i = i.lstrip(' ')
            i = i.rstrip(' ')
            data += [i]
        for x in data:
            x = x.split(':',1)
            if "Address" in x[0]:
                self._macList += [x[1]]
            if "Channel" in x[0]:
                self._chanList += [x[1]]
            if "Encryption key" in x[0]:
                self._encrboolList += [x[1]]
            if "ESSID" in x[0]:
                self._ssidList += [x[1].strip('"')]
            if "IE" in x[0] and "Unknown" not in x[1]:
                self._encryptList += [x[1]]
                
    def displayWifi(self):
        if len(self._macList) == 0:
            pass
        else:
            for i in range(len(self._macList)-1):
                print(self._ssidList[i],self._chanList[i],self._macList[i],self._encrboolList[i],self._encryptList[i])
    def getMacList(self):
        return self._macList
    def getSSIDList(self):
        return self._ssidList
    def getChanList(self):
        return self._chanList
    def getEncrBoolList(self):
        return self._encrboolList
    def getEncryptList(self):
        return self._encryptList
